package com.cloud.pole.cmpay.util;

/**
 * @Title: Test.java
 * @Package com.hisun.test
 * @Description: 
 * @Company: hisun
 * @author lv_hl
 * @date 2015年11月29日下午7:43:03
 * @version V1.0
 */

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName: Test
 * @Description:
 * @author lv_hl
 * @date 2015年11月29日下午7:43:03
 *
 */
public class Test {

	public static String sign(String clientId, String clientKey, String clientUserId)
			throws UnsupportedEncodingException {
		String str = "";
		String jsonStr = "{\"clientId\":\"" + clientId + "\",\"clientUserId\":\"" + clientUserId + "\"}";

		Map<String, Object> paramMap = new HashMap<String, Object>();
		String codes = "";
		try {
			paramMap = getJosn(jsonStr);
			codes = requestDataSort(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}

		codes = URLEncoder.encode(codes, "UTF-8");
		String messageSignStr = SHA_1(codes);
		messageSignStr = jsonStr + messageSignStr;
		String jsonValue = XXTEA.encryptWithBase64(messageSignStr.getBytes(), clientKey.getBytes());
		System.out.println("json报文\n" + jsonValue);
		String reqData = "{\"reqData\":\"" + jsonValue + "\",\"clientId\":\"" + clientId + "\"}";
		System.out.println("加密后请求报文\n" + reqData);
		str = reqData;
		return str;
	}

	private static String requestDataSort(Map<String, Object> map) throws Exception {
		String[] keyArray = (String[]) map.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);

		StringBuilder stringBuilder = new StringBuilder();
		String[] arrayOfString1;
		int j = (arrayOfString1 = keyArray).length;
		for (int i = 0; i < j; i++) {
			String key = arrayOfString1[i];
			String mapValue = map.get(key).toString();
			if (mapValue.startsWith("[{") && mapValue.endsWith("}]")) {
				mapValue = mapValue.substring(1, mapValue.length());
				mapValue = mapValue.substring(0, mapValue.length() - 1);
				if (StringUtils.isBlank(mapValue)) {
					stringBuilder.append(key).append("{}");
				} else {
					Map<String, Object> tempMap = new HashMap<String, Object>();
					tempMap = convertStringToMap(mapValue);
					String requestData = requestDataSort(tempMap);
					stringBuilder.append(key).append("{").append(requestData).append("}");
				}
			} else {
				stringBuilder.append(key).append(mapValue);
			}
		}
		return stringBuilder.toString();
	}

	public static Map<String, Object> convertStringToMap(String request) {
		if (request.startsWith("{")) {
			request = request.substring(1, request.length());
		}
		if (request.endsWith("}")) {
			request = request.substring(0, request.length() - 1);
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String[] out = request.split(",");
		for (String anOut : out) {
			String key = anOut.substring(0, anOut.indexOf("="));
			String value = anOut.substring(anOut.indexOf("=") + 1, anOut.length());
			paramMap.put(key.trim(), value.trim());
		}
		return paramMap;
	}

	/**
	 * 将整个json字符串解析，并放置到map<String,Object>中
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static String SHA_1(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static Map<String, Object> getJosn(String jsonStr) throws Exception {
		Map<String, Object> map = new HashMap();
		if (!StringUtils.isEmpty(jsonStr)) {
			JSONObject json = JSONObject.parseObject(jsonStr);
			for (String key : json.keySet()) {
				if (key.equals("baseInfo")) {
					JSONObject val = json.getJSONObject(key);
					for (String key1 : json.keySet()) {
						String value = val.getString(key1);
						if (value.indexOf("{") == 0) {
							map.put(key1.trim(), getJosn(value));
						} else if (value.indexOf("[") == 0) {
							map.put(key1.trim(), getList(value));
						} else {
							map.put(key1.trim(), value.trim());
						}
					}
				} else {
					String value = json.getString(key);
					if (value.indexOf("{") == 0) {
						map.put(key.trim(), getJosn(value));
					} else if (value.indexOf("[") == 0) {
						map.put(key.trim(), getList(value));
					} else {
						map.put(key.trim(), value.trim());
					}
				}
			}
		}
		return map;
	}

	/**
	 * 将单个json数组字符串解析放在list中
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static List<Map<String, Object>> getList(String jsonStr) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		JSONArray ja = JSON.parseArray(jsonStr);
		for (int j = 0; j < ja.size(); j++) {
			String jm = ja.get(j) + "";
			if (jm.indexOf("{") == 0) {
				Map<String, Object> m = getJosn(jm);
				list.add(m);
			}
		}
		return list;
	}

	public static void main(String[] args) {
		try {
			Test.sign("1", "2", "3");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
